package com.fingard.dsp.bank.directbank.jscb01;

import java.io.File;
import java.util.*;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class JSCB01Transaction extends JSCB01Base implements ITransaction {
    private Map<String, String> parseRespMsg(String[] retStrArr, RetAtsTrans retAts, String actArea) throws Exception {
        Map<String, String> resultMap = new HashMap();
        String tmpRespCode = "";
        String tmpRespInfo = "";
        if (retStrArr[0].length() == 0) {
            StringBuilder curSbMsg = new StringBuilder();
            XmlTextReader curBkReader = loadBankRespXmlReader(retStrArr[1], curSbMsg);
            if (curBkReader != null) {
                String curRetCode = curBkReader.getFirstText("/ap/head/ret_code");
                String curRetInfo = curBkReader.getFirstText("/ap/head/ret_info");
                String curDataMFS = "";
                if ("0000".equals(curRetCode)) {
                    int curRecordNum = Integer.parseInt(curBkReader.getFirstText("/ap/body/record_num"));
                    int curFieldNum = Integer.parseInt(curBkReader.getFirstText("/ap/body/field_num"));
                    if (curRecordNum > 0) {
                        String curFileFlag = curBkReader.getFirstText("/ap/head/file_flag");
                        if ("1".equals(curFileFlag)) {
                            String curFileName = curBkReader.getFirstText("/ap/body/file_name");
                            String curFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + curFileName;
                            WriteBankLogLn("读取前置数据文件：" + curFilePath);
                            curDataMFS = FileHelper.readFileText(curFilePath, getCharset());
                            WriteBankLogStep3(curDataMFS);
                        } else {
                            curDataMFS = curBkReader.getFirstText("/ap/body/serial_record");
                        }
                        if (curDataMFS != null) {
                            StringBuilder curSbLog = new StringBuilder();
                            ArrayList<String[]> curDataList = MFSHelper.getTextArray(curDataMFS, "|", curFieldNum, curRecordNum + 1, curSbLog);
                            if (curSbLog.length() == 0) {
                                //region **字段映射表
                                        /*
                                         0平台流水号（C20）     ｜1账号（C35）           ｜2货币码（C2）    　｜3交易日期（C8）   ｜4交易时间（C6）    ｜
                                         5主机流水号（C20）     ｜6交易行号(C12)         ｜7户名(C70)       　｜8对方账号(C35)    ｜9对方货币码(C2)    ｜
                                         10对方账号户名(C70)    ｜11对方账号开户行(C60)  ｜12对方行号(C12) 　 ｜13交易类别(C1)    ｜14钞汇标志(C1)     ｜
                                         15他行标志(C1)         ｜16同城异地标志(C1)     ｜17手续费(N16.2)    ｜18交易来源(C1)  　｜19发生额标志(C1)   ｜
                                         20被冲销流水号(C12)  　｜21原交易日期(C8)       ｜22现转标志(C1)     ｜23借贷标志(C1)    ｜24交易金额(N16.2)  ｜
                                         25余额(N16.2)          ｜26上笔余额(N16.2)      ｜27冻结金额(N16.2)  ｜28凭证种类(C20)   ｜29凭证批次号(C20)  ｜
                                         30凭证号码(C20)        ｜31交易码(C6)           ｜32柜员号(C10)      ｜33传票号(C20      ｜34摘要(C30)        ｜
                                         35附言(C60)          　｜36交易时间戳           ｜37冲正标志(C1)     ｜38备注字段二(C60　｜
                                         */
                                //endregion
                                for (int i = 1; i < curDataList.size(); i++) {
                                    String[] curRowDataArr = curDataList.get(i);
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    tmpRetDetail.actArea = actArea;
                                    tmpRetDetail.actNum = curRowDataArr[1].trim();
                                    tmpRetDetail.recAccNum = curRowDataArr[8].trim();
                                    tmpRetDetail.recAccName = curRowDataArr[10].trim();
                                    tmpRetDetail.recAccBank = StringHelper.convertToDBC(curRowDataArr[11]).trim();
                                    tmpRetDetail.tranDate = curRowDataArr[3].substring(0, 4)
                                            + "-" + curRowDataArr[3].substring(4, 6) + "-" + curRowDataArr[3].substring(6, 8);
                                    tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " +
                                            curRowDataArr[4].substring(0, 2) + ":" + curRowDataArr[4].substring(2, 4) + ":" + curRowDataArr[4].substring(4, 6);
                                    tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                    String cdFlagStr = curRowDataArr[23]; // D 1 表示借 C 2 表示贷
                                    String tranAmtStr = curRowDataArr[24];
                                    if ("C".equals(cdFlagStr)) {
                                        if (tranAmtStr.indexOf("-") >= 0) {
                                            tmpRetDetail.cdFlag = "1";
                                        } else {
                                            tmpRetDetail.cdFlag = "2";
                                        }
                                    } else if ("D".equals(cdFlagStr)) {
                                        if (tranAmtStr.indexOf("-") >= 0) {
                                            tmpRetDetail.cdFlag = "2";
                                        } else {
                                            tmpRetDetail.cdFlag = "1";
                                        }
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "借贷标志( " + cdFlagStr + ")无法识别，请与银行核对";
                                        break;
                                    }
                                    tmpRetDetail.tranAmt = curRowDataArr[24].replace("-", "");
                                    tmpRetDetail.accBal = curRowDataArr[25];
                                    tmpRetDetail.postTimestamp = curRowDataArr[36];
                                    tmpRetDetail.billType = curRowDataArr[28];
                                    tmpRetDetail.billNum = curRowDataArr[30];
                                    tmpRetDetail.usage = curRowDataArr[34];
                                    tmpRetDetail.abstr = pickupAbstr(curRowDataArr[35]);
                                    tmpRetDetail.payCode = curRowDataArr[32];
                                    tmpRetDetail.comment = StringHelper.joinNotEmpty(";", curRowDataArr[35], curRowDataArr[38]);
//                                    tmpRetDetail.askNumber = "";
//                                    tmpRetDetail.reqBatchNO = curRowDataArr[29];
                                    tmpRetDetail.cur = this.convertCurToATS(curRowDataArr[2]);
//                                    tmpRetDetail.seqId = "";
//                                    tmpRetDetail.isCollection = "";
                                    tmpRetDetail.originator = curRowDataArr[32];
                                    tmpRetDetail.busType = curRowDataArr[13];
                                    //ATSES-24143 dsp添加江苏银行电子回单匹配字段
                                    /**银行流水号（交易，支付提交时银行返回的流水号）*/
                                    tmpRetDetail.bnkSeqNo = curRowDataArr[0].trim();
                                    /**业务参考号，无电子回单编号时，通过业务参考号关联电子回单*/
                                    tmpRetDetail.busRef = curRowDataArr[1].trim() + curRowDataArr[8].trim() + curRowDataArr[3].trim();//本方账号+对方账号+日期yyyyMMdd

                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = curSbLog.toString();
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = "数据为空";
                        }
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = curRetInfo;
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = curSbMsg.toString();
            }
        } else {
            tmpRespCode = "-1";
            tmpRespInfo = retStrArr[1];
        }
        resultMap.put("tmpRespCode", tmpRespCode);
        resultMap.put("tmpRespInfo", tmpRespInfo);
        return resultMap;
    }

    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {

        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            //region 一：参数定义
            Calendar qryFromCldar = Calendar.getInstance();        //记录整个查询开始日期的日历
            Calendar qryToCldar = Calendar.getInstance();          //记录整个查询截止日期的日历
            Calendar curQryFrom = Calendar.getInstance();          //本次分月查询开始日期（日历）
            Calendar curQryTo = Calendar.getInstance();            //本次分月查询结算日期（日历）
            //endregion

            //region 二：参数值初始化
            qryFromCldar.setTime(p_req7516.getDateFrom());      //设置整个查询开始日期
            qryToCldar.setTime(p_req7516.getDateTo());          //设置整个查询截止日期
            curQryFrom.setTime(qryFromCldar.getTime());         //设置本次查询开始日期
            //endregion

            //region 三：按自然月，分月（页）查询
            while (curQryFrom.compareTo(qryToCldar) <= 0 && tmpRespCode.length() == 0) {

                //region【1】计算本次查询截止日期
                if (DateHelper.compareMonth(curQryFrom, qryToCldar) == -1) {
                    //开始日期 与 截止日期 为 跨月关系时，查本月信息
                    curQryTo.setTime(curQryFrom.getTime());
                    curQryTo.set(Calendar.DAY_OF_MONTH, curQryTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    //开始日期 与 截止日期 为 同月关系时，查全部信息
                    curQryTo.setTime(qryToCldar.getTime());
                }
                //endregion

                //region【2】组装查询报文
                XmlTextWriter xmlWriter = new XmlTextWriter();
                JSCB01Header bankHeader = new JSCB01Header();
                bankHeader.transCode = "200110";//交易代码
                bankHeader.reqSeqNo = p_req7516.reqHeader.transSeqID;

                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("body");
                xmlWriter.writeElementString("acno", p_req7516.actNum);
                xmlWriter.writeElementString("cur_code", convertCurToBank(p_req7516.actCur));
                xmlWriter.writeElementString("start_date", Format.Date8Format.format(curQryFrom.getTime()));
                xmlWriter.writeElementString("end_date", Format.Date8Format.format(curQryTo.getTime()));
                xmlWriter.writeEndElement();//body
                xmlWriter.writeEndElement();//ap
                xmlWriter.writeEndDocument();
                //endregion

                //region【3】发送请求报文
                String[] retStrArr = sendToBank(xmlWriter.toXmlString());
                //endregion

                //region【4】解析响应报文
                Map<String, String> parseResultMap = parseRespMsg(retStrArr, retAts, p_req7516.actArea);
                tmpRespCode = parseResultMap.get("tmpRespCode");
                tmpRespInfo = parseResultMap.get("tmpRespInfo");
                //endregion

                //region 【5】增加月数，继续查询
                curQryFrom.setTime(curQryTo.getTime());
                curQryFrom.add(Calendar.DAY_OF_MONTH, 1);
                //endregion
            }
            //endregion
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespInfo(tmpRespInfo);
            retAts.writeRespCode(tmpRespCode);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
//        RetAtsTrans retAts = new RetAtsTrans(p_req7515.reqHeader);
//        retAts.writeStart();
//        String tmpRespCode = "";
//        String tmpRespInfo = "";
//        try {
//            XmlTextWriter xmlWriter = new XmlTextWriter();
//            JSCB01Header bankHeader = new JSCB01Header();
//            bankHeader.transCode = "200109";//交易代码
//            bankHeader.reqSeqNo = p_req7515.reqHeader.transSeqID;
//
//            writeCommonHeader(xmlWriter, bankHeader);
//            xmlWriter.writeStartElement("body");
//            xmlWriter.writeElementString("acno", p_req7515.actNum);
//            xmlWriter.writeElementString("cur_code", convertCurToBank(p_req7515.actCur));
//            xmlWriter.writeEndElement();//body
//            xmlWriter.writeEndElement();//ap
//            xmlWriter.writeEndDocument();
//
//            String[] retStrArr = sendToBank(xmlWriter.toXmlString());
//
//            Map<String, String> parseResultMap = parseRespMsg(retStrArr, retAts, p_req7515.actArea);
//            tmpRespCode = parseResultMap.get("tmpRespCode");
//            tmpRespInfo = parseResultMap.get("tmpRespInfo");
//        } catch (Exception e) {
//            tmpRespCode = "-1";
//            tmpRespInfo = e.getMessage();
//            e.printStackTrace();
//        }
//        if ("-1".equals(tmpRespCode)) {
//            retAts = new RetAtsTrans(p_req7515.reqHeader);
//            retAts.writeStart();//写返回ATS的统一头部信息
//            retAts.writeRespInfo(tmpRespInfo);
//            retAts.writeRespCode(tmpRespCode);
//        } else if (retAts.getWrittenRdCount() == 0) {
//            retAts.writeRespInfo("交易为空");
//            retAts.writeRespCode("0");
//        }
//        retAts.writeEnd();
//        return retAts;

        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
